<template>
  <div class="city spage">
    <myhead :title="$route.query.name?'当前城市-('+$route.query.name+')':'城市选择'" :back="true"/>
    <van-search v-model="keyword" show-action placeholder="请输入城市名或者拼音" @cancel="cancel" @search="searchcity"/>
    <van-index-bar v-if="flag">
      <div v-for="(l,i) in pylist" :key="i">
          <van-index-anchor :index="l" />
          <van-cell @click="choosecity(city)" v-for="(city,index) in list.filter(item=>item.pinyin.indexOf(l.toLowerCase())==0) " :key="index">
              {{city.name}}
          </van-cell>
      </div>
    </van-index-bar>
    <div v-else >
      <van-cell @click="choosecity(city)" v-for="(city,index) in list" :key="index">
          {{city.name}}
      </van-cell>
    </div>
  </div>
</template>

<script>
export default {
  data(){
    return {
      flag:true,
      keyword:'',
      list:[],
      pylist:[
        "A",
        "B",
        "C",
        "D",
        "E",
        "F",
        "G",
        "H",
        "I",
        "J",
        "K",
        "L",
        "M",
        "N",
        "O",
        "P",
        "Q",
        "R",
        "S",
        "T",
        // "U",
        // "V",
        "W",
        "X",
        "Y",
        "Z",
      ]
    }
  },
  methods:{
    cancel(){
      console.log('cancel')
      this.flag = true;
      this.list = [...this.cityList];
    },
    searchcity(value){
      console.log(value)
      this.flag = false;
      this.list = this.cityList.filter(item=>(item.name.indexOf(value)!=-1||item.pinyin.indexOf(value)!=-1));
    },
    choosecity(city){
        this.changeCity(city);
        this.$router.go(-1);
    }
  },
  beforeRouteLeave(to,from,next){
    if(this.city){
      next()
    }else{
       this.$toast("请先确认城市再离开.")
       next(false);
    }
  },
  mounted(){ 
      this.$ajax.getMaiZuo({},{
        'X-Host': 'mall.film-ticket.city.list'
      })
      .then(res=>{
        console.log(res);
        this.changeCityList(res.data.cities);
        this.list = res.data.cities; 
      })
   }
}
</script>
